package com.zenglx.assembly.increasingSequence.impl;

import com.zenglx.assembly.increasingSequence.api.SequenceGeneratorApi;
import com.zenglx.assembly.increasingSequence.api.SequenceGeneratorConstant;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis 序列生成器
 * @author zengliangxi
 */
@Log4j2
@ConditionalOnProperty(name = SequenceGeneratorConstant.SEQUENCE_GENERATOR_TYPE
        , havingValue = SequenceGeneratorConstant.SEQUENCE_GENERATOR_TYPE_REDIS)
@Component
public class RedisSequenceGenerator implements SequenceGeneratorApi {

    @Value("${com.zenglx.assembly.sequenceGenerator.namespace:com-zenglx-assembly}")
    private String redisNameSpace;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据key获取下一个序列，如果key不存在，则生成此key的序列，从0开始
     *
     * @return id
     */
    @Override
    public String nextId(String key) {
        String newKey = redisNameSpace+":"+key;
        long sequence = getSequence(newKey,-1);
        //log.info("key:{};获取的递增值为:{}",newKey,sequence);
        return String.valueOf(sequence);
    }


    /**
     * 从redis获取递增序列
     * @param key
     * @param liveTime
     * @return
     */
    private Long getSequence(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {
            //初始设置过期时间,单位毫秒
            entityIdCounter.expire(liveTime, TimeUnit.MILLISECONDS);
        }
        return increment;
    }

}
